/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.prolificinteractive.materialcalendarview.ext;

import ohos.app.Context;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import org.threeten.bp.zone.TzdbZoneRulesProvider;
import org.threeten.bp.zone.ZoneRulesInitializer;
import org.threeten.bp.zone.ZoneRulesProvider;

import java.io.IOException;

/**
 * ThreeTen初始化
 *
 * @since 2021-07-02
 */
public class MaterialCalendarViewInit {
    private static final String TAG = "MaterialCalendarViewInit";
    private static final String TZDB_DAT = "TZDB.dat";
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.DEBUG, 110, TAG);

    /**
     * 初始化ThreeTen依赖
     *
     * @param context 上下文
     */
    public static void initThreeTen(Context context) {
        ZoneRulesInitializer.setInitializer(new ZoneRulesInitializer() {
            @Override
            protected void initializeProviders() {
                Resource resource = null;
                TzdbZoneRulesProvider provider = null;
                try {
                    ResourceManager resManager = context.getResourceManager();
                    RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/" + TZDB_DAT);
                    resource = rawFileEntry.openRawFile();
                    provider = new TzdbZoneRulesProvider(resource);
                } catch (IOException ex) {
                    HiLog.error(LABEL, ex.getMessage());
                } finally {
                    if (resource != null) {
                        try {
                            resource.close();
                        } catch (IOException ex) {
                            HiLog.error(LABEL, ex.getMessage());
                        }
                    }
                }
                ZoneRulesProvider.registerProvider(provider);
            }
        });
    }
}
